/**
 * Proyecto: Karma
 * @author Mislas
 */

Karma.List.AggregateList = Ext.extend(Karma.List.ListBase, {
	entityName: null,
	entity: null,
	parentEntity: null,
	context: null,
	showSearch: false,
	isLoaded: false,
	initComponent: function(){
		if (PLOG.isDebugEnabled()) {
			PLOG.debug('[AggregateList.initComponent] <- Entity Name: ' + this.entityName);
		}
		Karma.List.AggregateList.superclass.initComponent.apply(this, arguments);
		this.addEvents({ 'change': true, 'refresh': true });
		
		this.on('afterlayout', function() {
	 		if (PLOG.isDebugEnabled()) {
				PLOG.debug('[AggregateList.afterlayout] <- Id: ' + this.id +
					', parentEntity: ' + this.parentEntity);
			}
			if(!this.isLoaded) {
				if (this.parentEntity != null && this.parentEntity.Id > 0) {
					this.setContext(this.parentEntity);
					this.getStore().reload();
					this.isLoaded = true;
					this.enable();
				} else {
					if (this.parentEntity == null || this.parentEntity.Id == 0) {
						this.disable();
					}
				}
			}
    	}, this);
	},

	newRecord: function(){
		if (PLOG.isDebugEnabled()) {
			PLOG.debug('[AggregateList.newRecord] <-');
		}
		var reload = this.reload.createDelegate(this);
		this.entity.NewFromEntity(this.getParentParameters(), { 
			flush: {
				fn: function(result, form){
					reload();
				}, scope: this
			}
		});
	},
	
	getParentParameters: function() {
		return { Id: this.parentEntity.Id };
	},
	
	openRecord: function(id){
		if (PLOG.isDebugEnabled()) {
			PLOG.debug('[AggregateList.openRecord] <-');
		}
		if (!(this.canOpen && this.security.Open)) {
			if (PLOG.isDebugEnabled()) {
				PLOG.debug('[AggregateList.openRecord] User does not have permissions. Open: ' +
					this.security.Open + ', canOpen: ' + this.canOpen);
			}
			return;
		}
		var reload = this.reload.createDelegate(this);
		this.entity.Open(id, {
				'flush': {
					fn: function(win){
						reload();
					}
				}, 
				scope: this 
			}, 
			null, {
				canUpdate: this.canUpdate
			});
	},

	deleteRecord: function(id) {
		if (PLOG.isDebugEnabled()) {
			PLOG.debug('[AggregateList.deleteRecord] <-');
		}
		this.entity.Delete(id, {
			fn: function(){
				this.reload();
			},
			scope: this
		});
	},

	setParentEntity: function(v){
		if (PLOG.isDebugEnabled()) {
			PLOG.debug('[AggregateList.setParentEntity] <- value: ' + v);
		}
		this.parentEntity = v;
		this.updateControls.createDelegate(this)(v);
		this.setContext(v);
		this.enable();
	},
	
	getParentEntity: function(){
		return this.parentEntity;
	},
	
	setContext: function(value) {
		if (PLOG.isDebugEnabled()) {
			PLOG.debug('[AggregateList.setContext] Id: ' + value);
		}
		if (!Ext.isEmpty(this.context) && value.Id > 0) {;
			this.context = this.context.replace('?', value.Id);
			this.getStore().baseParams.Parameters.SubQuery = this.context;
		}
	},

	getTBarControls: function() {
		return [this.newToolbarButton = new Ext.Button({
			xtype: 'button',
			text: 'Agregar...',
			iconCls: 'icon-plus',
			handler: this.newRecord,
			scope: this
		}), this.exportBtn = new Ext.Button({
            text: 'Exportar',
            handler: this.onExportExcel,
			iconCls: 'icon-export',
            scope: this,
            hidden: !this.security.Export
        }), '->', this.searchfield = new Ext.ux.SearchField({
            anchor: '50%',
            store: this.getStore(),
			value: ''
        })];
	},
    
    getGridControl: function() { 
        var listeners = this.getGridListeners();
        var columns = this.getGridColumns(Ext.isEmpty(this.query) ? null : this.query.Columns);
        var plugins = this.getPlugins(columns);
        var sm = this.getSelectionModel();
        var grid = {
            xtype: 'grid',
            id: this.getId() + '-grid',
            border: false,
			columnLines: true,
            frame: false,
            store: this.getStore(),
            cm: new Ext.grid.ColumnModel(columns),
            stripeRows: true,
            sm: sm,
            listeners: listeners,
            view: this.getGridView(),
            loadMask: true,
            plugins: plugins
        };
        return grid;
    },
	
	processStore: function() {
		if (PLOG.isDebugEnabled()) {
			PLOG.debug('[AggregateList.processStore] <-' + this.id + ', Context: ' + 
				this.context + ', Service: ' + this.service);
		}
        var _fields;
        if (Ext.isEmpty(this.query)) {
        	_fields = Karma.Factory.ColumnFactory.getColumnStore(this.entity.columns);
        } 
        else {
	        _fields = this.getStoreColumns(this.query.Columns);
		}
		var store = Karma.Data.GroupingStore.create(
			this.service, _fields, null,{
			Query: this.query? this.query.Id: this.metadata.LinkQuery,
			SubQuery: this.context,
			Criteria: '',
			Start: 0,
			PageSize: Karma.Conf.DefaultPageSize 
		});
		return store;
	},
	
	reload: function() {
		this.getStore().baseParams.Parameters.SubQuery = this.context;
		this.getStore().reload();
		this.fireEvent('refresh');
	},
	
    onExportExcel: function(){
       var form = Ext.DomHelper.append(document.body, {
            id: 'export_form',
            tag: 'form',
            cls: 'x-hidden',
            method: 'GET',
            action: 'Service/Exporter',
            target: '_self',
            children: [
                { name: 'Service', tag: 'input', type: 'hidden', value: this.service },
                { name: 'Method', tag: 'input', type: 'hidden', value: Karma.Conf.FindMethod },
                { name: 'Parameters', tag: 'input', type: 'hidden', 
                    value: Ext.encode({
						Query: this.query? this.query.Id: this.metadata.LinkQuery,
						SubQuery: this.context,
                        Criteria: '',
                        Start: 0,
                        PageSize: 0
                    }) 
                }
            ]
        });
		form.submit();
    },
	
	updateControls: function(value) {
		Karma.List.AggregateList.superclass.updateControls.apply(this, arguments);
		// toolbar config
		if (!this.canNew) {
			this.newToolbarButton.disable();
		}
		if (!this.canDelete) {
			this.deleteMenuAction.disable();
		}
	}

});

Karma.AL = Karma.List.AggregateList;
Ext.reg('ag.list', Karma.AL);
